<?php
namespace plugins\php_qrcode;

use cmf\lib\Plugin;

use cmf\lib\Storage;

use think\File;
require_once  'lib'  . DIRECTORY_SEPARATOR . 'phpqrcode.php';

class PhpQrcodePlugin extends Plugin {
    public $info = array(
        'name'        => 'PhpQrcode',
        'title'       => 'php二维码生成工具',
        'description' => '直接配置参数生成二维码并返回图片存储地址，支持OSS存储',
        'status'      => 1,
        'author'      => 'Forpastime',
        'version'     => '1.0'
    );

    public $hasAdmin = 1;//插件是否有后台管理界面

    // 插件安装
    public function install()
    {
        return true;//安装成功返回true，失败false
    }

    // 插件卸载
    public function uninstall()
    {
        return true;//卸载成功返回true，失败false
    }

    public function createQRcode($param)
    {

        if(empty($param) || empty($param['content'])){
            return ('请传入二维码内容');
        }

        $config = cmf_get_plugin_config('PhpQrcode');
        
        $dir = dirname(WEB_ROOT .'upload/qrcode/xx');
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }
        $data = $param['content'];//内容
        $level = !empty($config['level'])?$config['level']:'L';// 纠错级别：L、M、Q、H
        $size = !empty($config['size'])?intval($config['size']):3;//元素尺寸
        $margin = !empty($config['margin'])?intval($config['margin']):3;//边距
        $outfile = WEB_ROOT . DIRECTORY_SEPARATOR . 'upload'. DIRECTORY_SEPARATOR .'qrcode'. DIRECTORY_SEPARATOR.time().'.png';

        $imagePath = 'qrcode/'.time().'.png';
        // var_dump($outfile);
        // die;
        $saveandprint = !empty($config['saveandprint'])?intval($config['saveandprint']):false;// true直接输出屏幕  false 保存到文件中
        $back_color = !empty($config['back_color'])?str_replace('#','0x',hexdec($config['back_color'])):0xFFFFFF;//白色底色
        $fore_color = !empty($config['fore_color'])?str_replace('#','0x',hexdec($config['fore_color'])):0x000000;//黑色二维码色 若传参数要hexdec处理，如 $fore_color = str_replace('#','0x',$fore_color); $fore_color = hexdec('0xCCCCCC');

        $qrcode = new \QRcode();
        //生成png图片
        $qrcode->png($data, $outfile, $level, $size, $margin, false, $back_color, $fore_color);
        
        //接下来做上传
        sleep($config['wait_time']);
        $storage = cmf_get_option('storage');
        $result['url'] = $result['preview_url']='';
        //是否要上传到云存储
        if ( $storage['type'] != 'Local') {
            $storageObj   = new Storage($storage['type'], $storage['storages'][$storage['type']]);
            
            $result = $storageObj->upload($imagePath, $outfile, 'image');
            if ( $storage['type'] == 'Qiniu') {
                $qiniuSetting   = cmf_get_plugin_config('Qiniu');
                if(!$qiniuSetting){
                    return ('七牛云存储插件异常');
                }
                $count = substr_count($result['preview_url'],'http');//出现http或https的次数
                if($count>1){
                    if(strpos($result['preview_url'],'https')){
                        $url = explode($qiniuSetting['style_separator'],substr($result['preview_url'],8));
                    }else{
                        $url = explode($qiniuSetting['style_separator'],substr($result['preview_url'],7));
                    }
                    $result['url'] = $result['preview_url'] = $url['0'];
                }
                $result['url'] = $result['preview_url'] = $url['0'];
                
            }
        }else{
            $result['type'] ='local';
            $result['url']= $result['preview_url'] = cmf_get_file_download_url($imagePath);
        }

        if (!empty($result['preview_url'])) {
            return $result;
        } else {
            echo "上传失败!";
        }
        
    }

    //上传图片
    public function uploadImage($imagePath, $outfile, $fileType)
    {

        $strFileExtension = $fileType;//png方法统一图片为image
        $option = cmf_get_option('storage');
        $type = $option['type'];

        $uploadSetting = cmf_get_upload_setting();

        $arrFileTypes = [
            'image' => ['title' => 'Image files', 'extensions' => $uploadSetting['file_types']['image']['extensions']],
            'video' => ['title' => 'Video files', 'extensions' => $uploadSetting['file_types']['video']['extensions']],
            'audio' => ['title' => 'Audio files', 'extensions' => $uploadSetting['file_types']['audio']['extensions']],
            'file'  => ['title' => 'Custom files', 'extensions' => $uploadSetting['file_types']['file']['extensions']]
        ];

        $fileUploadMaxFileSize = $uploadSetting['upload_max_filesize'][$strFileExtension];
        $fileUploadMaxFileSize = empty($fileUploadMaxFileSize) ? 2097152 : $fileUploadMaxFileSize;//默认2M

        $strSaveFilePath = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'data'. DIRECTORY_SEPARATOR .'1605182489.png';
        $strId = $fileSaveName = '1605182489.png';
        $dir = dirname(WEB_ROOT .'upload/qrcode/xx');
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }

        $strWebPath = "";
        $fileType = 'image';
        $strWebPath = "";
        $fileImage = new File($strSaveFilePath, 'r');
        // var_dump($fileImage);
        $arrInfo   = [
            "name"     => '二维码',
            "type"     => $fileImage->getMime(),
            "tmp_name" => $strSaveFilePath,
            "error"    => 0,
            "size"     => $fileImage->getSize(),
        ];

        $fileImage->setSaveName($fileSaveName);
        $fileImage->setUploadInfo($arrInfo);
        $storage = cmf_get_option('storage');
        $uploadPath = WEB_ROOT . DIRECTORY_SEPARATOR. 'upload' . DIRECTORY_SEPARATOR;

        $needUploadToRemoteStorage = false;//是否要上传到云存储
        if ( $storage['type'] != 'Local') {
            $needUploadToRemoteStorage = true;
        } 
        // var_dump($arrInfo['tmp_name']);die;

        // $uploader = new Upload();
        if ($storage['type'] != 'Local') { //  增加存储驱动
            $watermark = cmf_get_plugin_config($storage['type']);
            $storage   = new Storage($storage['type'], $storage['storages'][$storage['type']]);

            if ($needUploadToRemoteStorage) {
                session_write_close();
                if(file_exists($uploadPath . 'qrcode' . DIRECTORY_SEPARATOR)){
                    chmod($uploadPath . 'qrcode' . DIRECTORY_SEPARATOR,0777);
                }
                $result = $storage->upload($arrInfo['tmp_name'], $strWebPath.time().'png', $fileType);
               
                if (!empty($result)) {
                    var_dump($needUploadToRemoteStorage);
                die;
                    // return array_merge([
                    //     'filepath'    => $arrInfo["file_path"],
                    //     "name"        => $arrInfo["filename"],
                    //     // 'id'          => $strId,
                    //     'preview_url' => cmf_get_root() . '/upload/' . $arrInfo["file_path"],
                    //     'url'         => cmf_get_root() . '/upload/' . $arrInfo["file_path"],
                    // ], $result);
                }
            }


        }
    }
}